<template>
	<div class="panel-content-wrap">
		<div class="panel-button panel-margin-top">
			<el-button-group>
				<el-button type="primary" @click="currentData = 'static'" :disabled="currentData == 'static'">静态数据</el-button>
				<el-button type="primary" @click="currentData = 'rest'" :disabled="currentData == 'rest'">接口数据</el-button>
			</el-button-group>
		</div>
		<div class="panel-setting-center">
			<template v-if="currentData === 'static'" v-for="(item, i) in data.properties?.dataList?.static">
				<div class="panel-list-head">
					<span style="font-size: 14px">数据-{{ item.name }}</span>
					<span @click="deleteDatabase('static', i)"><SvgIcon name="delete" :size="14" /></span>
				</div>
				<el-divider />
			</template>
			<template v-if="currentData === 'rest'" v-for="(item, i) in data.properties?.dataList?.rest">
				<div class="panel-list-head">
					<span style="font-size: 14px">数据-{{ item.title }}</span>
					<span @click="deleteDatabase('rest', i)"><SvgIcon name="delete" :size="14" /></span>
				</div>
				<el-divider />
			</template>
			<el-button icon="Plus" type="primary" @click="addDataList" style="width: 100%">添加数据</el-button>
		</div>
	</div>

	<el-dialog v-model="staticDialog" width="80%" :show-close="false" center>
		<template #header> 设置静态数据源 </template>
		<template #footer>
			<span class="dialog-footer">
				<el-button type="primary" @click="saveStaticDatabase()">保存</el-button>
				<el-button @click="staticDialog = false">取消</el-button>
			</span>
		</template>
		<el-form :model="staticForm" label-position="left" label-width="100px">
			<el-form-item label="数据源名称: " prop="name" style="margin-top: 18px; margin-bottom: 18px">
				<el-input v-model="staticForm.name" placeholder="请输入名称" />
			</el-form-item>
			<div class="form-design-code-editor">
				<code-editor v-model="staticForm.code" lang="json" />
			</div>
		</el-form>
	</el-dialog>
	<el-dialog v-model="restDialog" width="80%" :show-close="false" center>
		<template #header> 设置数据源 </template>
		<template #footer>
			<span class="dialog-footer">
				<el-button type="primary" @click="saveRestDatabase()">保存</el-button>
				<el-button @click="restDialog = false">取消</el-button>
			</span>
		</template>
		<el-form ref="formRef" :model="restForm" label-position="left" label-width="100px">
			<el-form-item
				label="请求名: "
				prop="title"
				:rules="{
					required: true,
					message: '请输入名称',
					trigger: 'blur',
				}"
				style="margin-top: 18px; margin-bottom: 18px"
			>
				<el-input v-model="restForm.title" placeholder="请输入名称" />
			</el-form-item>
			<el-form-item
				label="请求地址: "
				prop="url"
				:rules="{
					required: true,
					message: '请输入地址',
					trigger: 'blur',
				}"
				style="margin-bottom: 18px"
			>
				<el-input v-model="restForm.url" placeholder="请输入地址">
					<template #prepend>
						<el-select v-model="restForm.method" style="width: 100px">
							<el-option label="GET" value="get" />
							<el-option label="POST" value="post" />
							<el-option label="PUT" value="put" />
							<el-option label="DELETE" value="delete" />
						</el-select>
					</template>
					<template #append>
						<el-button @click="testRequest">测试请求</el-button>
					</template>
				</el-input>
			</el-form-item>
			<el-tabs v-model="remoteTabs">
				<el-tab-pane :label="'请求头部Headers' + (restForm.headers.length ? '（' + restForm.headers.length + '）' : '')" name="headers">
					<el-row v-for="(header, index) in restForm.headers" :key="index" class="option-row" :gutter="5">
						<el-col :span="11">
							<el-input v-model="header.key" placeholder="Key" />
						</el-col>
						<el-col :span="11">
							<el-input v-model="header.value" placeholder="Value" />
						</el-col>
						<el-col :span="2" class="btn-del">
							<el-button type="primary" icon="Delete" circle @click="removeKeyValue('headers', index)"></el-button>
						</el-col>
					</el-row>
					<el-button link type="primary" style="margin: 10px 0px 10px 0px" @click="addKeyValue('headers')">增加头部</el-button>
				</el-tab-pane>
				<el-tab-pane :label="'请求参数Params' + (restForm.params.length ? '（' + restForm.params.length + '）' : '')" name="params">
					<el-row v-for="(param, index) in restForm.params" :key="index" class="option-row" :gutter="5">
						<el-col :span="11">
							<el-input v-model="param.key" placeholder="Key" />
						</el-col>
						<el-col :span="11">
							<el-input v-model="param.value" placeholder="Value" />
						</el-col>
						<el-col :span="2" class="btn-del">
							<el-button type="primary" icon="Delete" circle @click="removeKeyValue('params', index)"></el-button>
						</el-col>
					</el-row>
					<el-button link type="primary" style="margin: 10px 0px 10px 0px" @click="addKeyValue('params')">增加参数</el-button>
				</el-tab-pane>
				<el-tab-pane :label="'请求数据Data' + (restForm.data.length ? '（' + restForm.data.length + '）' : '')" name="data">
					<el-row v-for="(data, index) in restForm.data" :key="index" class="option-row" :gutter="5">
						<el-col :span="11">
							<el-input v-model="data.key" placeholder="Key" />
						</el-col>
						<el-col :span="11">
							<el-input v-model="data.value" placeholder="Value" />
						</el-col>
						<el-col :span="2" class="btn-del">
							<el-button type="primary" icon="Delete" circle @click="removeKeyValue('data', index)"></el-button>
						</el-col>
					</el-row>
					<el-button link type="primary" style="margin: 10px 0px 10px 0px" @click="addKeyValue('data')">增加数据</el-button>
				</el-tab-pane>
			</el-tabs>
			<el-collapse model="request">
				<el-collapse-item title="处理请求数据" name="request">
					<div class="form-design-code-editor">
						<div class="code-editor-tip">(config) => {</div>
						<code-editor v-model="restForm.requestHandler" lang="javascript" />
						<div class="code-editor-tip">}</div>
					</div>
				</el-collapse-item>
				<el-collapse-item title="处理响应数据" name="response">
					<div class="form-design-code-editor">
						<div class="code-editor-tip">(response) => {</div>
						<code-editor v-model="restForm.responseHandler" lang="javascript" />
						<div class="code-editor-tip">}</div>
					</div>
				</el-collapse-item>
				<el-collapse-item title="错误处理" name="error">
					<div class="form-design-code-editor">
						<div class="code-editor-tip">(error) => {</div>
						<code-editor v-model="restForm.errorHandler" lang="javascript" />
						<div class="code-editor-tip">}</div>
					</div>
				</el-collapse-item>
			</el-collapse>
		</el-form>
	</el-dialog>
</template>

<script setup lang="ts">
import { inject, ref, watch } from 'vue';
import createRequest from '../../../../../utils/request';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
import { usePropertiesPanelData } from '../../../useapi';

const data = usePropertiesPanelData();

const currentData = ref('static');

const restForm = ref<any>({});
const staticForm = ref<any>({});

const remoteTabs = ref('headers');
const formRef = ref();

const restDialog = ref(false);
const staticDialog = ref(false);

const addDataList = () => {
	if (currentData.value === 'static') {
		data.properties.dataList = data.properties.dataList ? data.properties.dataList : [];
		if (typeof data.properties.dataList.static === 'undefined') {
			data.properties.dataList.static = [];
		}
		staticDialog.value = true;
		staticForm.value = {
			name: '',
			code: '',
		};
	}
	if (currentData.value === 'rest') {
		data.properties.dataList = data.properties.dataList ? data.properties.dataList : {};
		if (typeof data.properties.dataList.rest === 'undefined') {
			data.properties.dataList.rest = [];
		}
		restDialog.value = true;
		restForm.value = {
			title: '',
			url: '',
			method: 'get',
			headers: [],
			params: [],
			data: [],
			requestHandler: 'return config;',
			responseHandler: 'return response.data;',
			errorHandler: 'return Promise.reject(error);',
		};
	}
};

const saveStaticDatabase = () => {
	data.properties.dataList.static.push(staticForm.value);
	console.log('dataList.static', data.properties.dataList.static);
	staticDialog.value = false;
};

const saveRestDatabase = () => {
	data.properties.dataList.rest.push(restForm.value);
	restDialog.value = false;
};

const testRequest = () => {
	formRef.value.validateField(`restForm.url`).then(() => {
		const loading = ElLoading.service({
			lock: true,
			text: 'Loading',
			background: 'rgba(0, 0, 0, 0.7)',
		});
		createRequest(restForm)
			.then((data: any) => {
				loading.close();
				ElMessageBox.alert(JSON.stringify(data, null, '\t'), '响应结果');
			})
			.catch((error: any) => {
				loading.close();
				ElMessage.error(error.message);
			});
	});
};

const addKeyValue = (attr: string) => {
	restForm.value[attr].push({ key: '', value: '' });
};

const removeKeyValue = (attr: string, targetIndex: number) => {
	restForm.value[attr].splice(targetIndex, 1);
};

const deleteDatabase = (type: string, index: number) => {
	if (type === 'static') {
		data.properties?.dataList?.static.splice(index, 1);
	}
	if (type === 'rest') {
		data.properties?.dataList?.rest.splice(index, 1);
	}
};
</script>

<style lang="scss" scoped>
.option-row {
	margin-top: 5px;
}
</style>
